package com.pay.controller;

import com.alibaba.fastjson.TypeReference;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.group.common.utils.R;
import com.pay.config.AlipayTemplate;
import com.pay.fegin.OrderFeignService;
import com.pay.service.AlipayService;
import com.pay.vo.PayAsyncVo;
import com.pay.vo.PayVo;
import com.pay.vo.ShopOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lins
 * @date 2021/10/19 18:52
 */
@Slf4j
@Controller
@RequestMapping("alipay")
public class AlipayController {
    @Autowired
    private AlipayTemplate alipayTemplate;
    @Autowired
    private OrderFeignService orderFeignService;
    @Autowired
    private AlipayService alipayService;
    /*
    * 支付成功以后响应一个支付页
    * 格式为text/html
    * */
    @RequestMapping(value = "pay",produces = "text/html")
    @ResponseBody
    public String pay(@RequestParam String orderSn){
        R r = orderFeignService.getOrderInfoByOrderSn(orderSn);
        if (r.getCode()==0){
            ShopOrderVo data = r.getData(new TypeReference<ShopOrderVo>() {
            });
            PayVo payVo = new PayVo();
            payVo.setOut_trade_no(data.getOrderSn());
            payVo.setSubject("秒杀商品");
            payVo.setTotal_amount(data.getOrderPayPrice());
            String pay = null;
            try {
                pay = alipayTemplate.pay(payVo);
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
            return pay;
        }
        return null;
    }

    /**
     *交易查询
     */
    @RequestMapping("/transactionQuery")
    @ResponseBody
    public AlipayTradeQueryResponse transactionQuery(@RequestParam("tradeNo") String tradeNo){

        return alipayService.transactionQuery(tradeNo);
    }



    /*
    * 异步通知获取支付结果
    * 修改订单状态  添加支付表
    * */
    @PostMapping("/payed/notify")
    @ResponseBody
    public String notify(PayAsyncVo payAsyncVo, HttpServletRequest request) throws AlipayApiException {
        log.info("访问到异步回调方法");
        //需要验签
        Map<String, String> params = new HashMap<>();
        //从当前请求中获取参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (String name : parameterMap.keySet()) {
            String[] values = parameterMap.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决  出现乱码时启用此代码
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        boolean signVerified = AlipaySignature.rsaCheckV1(
                params,
                alipayTemplate.getAlipay_public_key(),
                alipayTemplate.getCharset(),
                alipayTemplate.getSign_type()
        );
        if (signVerified){
            log.info("支付宝异步回调验签成功");
            return orderFeignService.notify(payAsyncVo);
        }else {
            log.info("支付宝异步回调验签失败");
            return "error";
        }
    }
    /*
    * 退款
    * */
    @RequestMapping("rebund")
    @ResponseBody
    public AlipayTradeRefundResponse rebund(@RequestParam Integer examineId){
        return alipayService.rebund(examineId);
    }
}
